package com.service.impl;

import com.dao.CarouselFigureDao;
import com.dao.impl.CarouselFigureDaoImpl;
import com.pojo.CarouselFigure;
import com.pojo.PageBean;
import com.service.CarouselFigureService;
import com.utils.JDBCUtil;

import java.util.List;

public class CarouselFigureServiceImpl implements CarouselFigureService {
    private CarouselFigureDao dao = new CarouselFigureDaoImpl();

    /**
     * 分页查询方法
     * @param limit
     * @param current
     * @return
     */
    @Override
    public PageBean<CarouselFigure> findAll(int limit,int current) {
        int count = dao.selectCount();
        List<CarouselFigure> list = dao.findAll((current - 1) * limit, limit);
        PageBean<CarouselFigure> pageBean= new PageBean<>();
        pageBean.setData(list);
        pageBean.setCurrent(current);
        pageBean.setTotal(count);
        return pageBean;
    }

    /**
     * 添加方法
     * @param carouselFigure
     * @return
     */
    @Override
    public boolean addCF(CarouselFigure carouselFigure) {
        int maxSerialNumber = dao.findMaxSerialNumber();
        carouselFigure.setSequenceNum(maxSerialNumber+1);
        return dao.addCF(carouselFigure)>0;
    }

    /**
     * 根据ID删除用户
     * @param id
     * @return
     */
    @Override
    public boolean deleteCF(String id) {
        Integer num = dao.findByID(id).getSequenceNum();
        return dao.deleteCF(id)>0;
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public CarouselFigure findByID(String id) {
        return dao.findByID(id);
    }

    /**
     * 修改方法
     * @param carouselFigure
     * @return
     */
    @Override
    public boolean updateCF(CarouselFigure carouselFigure) {
        System.out.println("Service中的："+carouselFigure.toString());

        CarouselFigure cf = dao.findBySequenceNum(carouselFigure.getSequenceNum());//获取到被替代的元素的num

        if (cf==null){
            return  dao.updateCF(carouselFigure)>0;
        }else {
            try {
                Integer num = cf.getSequenceNum();//1
                cf.setSequenceNum(findByID(carouselFigure.getId()).getSequenceNum());//carouselFigure.getSequenceNum()=2
                carouselFigure.setSequenceNum(num);//1
                System.out.println("4"+carouselFigure);
                dao.updateCF(cf);
                dao.updateCF(carouselFigure);
                return true;
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return false;
    }

    /**
     * 获取最大的序号
     * @return
     */
    @Override
    public int findMaxSerialNumber() {
        return dao.findMaxSerialNumber();
    }
}
